package com.jet.chat.client;

import com.jet.chat.exception.ChatException;
import com.jet.chat.message.Message;
import com.jet.chat.message.MessageReader;
import com.jet.chat.message.MessageWriter;

public class ChatClientReaderThread implements Runnable {
	private MessageReader reader;
	private MessageWriter writer;
	private MessageWriter serverWriter;
	
	public ChatClientReaderThread(MessageReader reader, MessageWriter writer, MessageWriter serverWriter) {
		this.reader = reader;
		this.writer = writer;
		this.serverWriter = serverWriter;
	}

	@Override
	public void run() {
		Message chatMessage;
		try {
			int messageId;
			while (((chatMessage = reader.read()) != null) && (chatMessage.getContent() != null)) {
				if (chatMessage.getContent().equals("/q")) {
					System.out.println("quit command accepted");
					System.exit(0);
				} else {
					if (chatMessage.isReverse()) {
						serverWriter.write(chatMessage);
					} else {
						writer.write(chatMessage);
						messageId = chatMessage.getId();
						if (messageId != 0) {
							serverWriter.write("/rc " + chatMessage.getId());
						}
					}
				}
			}
			System.out.println("server gone offline");
			System.exit(0);
		} catch (ChatException e) {
			e.printStackTrace();
		}
		System.out.println("server gone offline");
		System.exit(0);
	}
	
}
